package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YYGHException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.prop.WeiXinProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:hx
 * @DateTime:2022/11/14 11:01
 * @Description:
 */
@Controller
@RequestMapping("/user/wx")
public class WeiXinController {

    @Autowired
    private WeiXinProperties weiXinProperties;
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/getLoginParam")
    @ResponseBody
    public R getLoginParam(){
        Map<String,Object> map = new HashMap<>();
        map.put("appid",weiXinProperties.getAppid());
        map.put("scope",weiXinProperties.getScope());
        map.put("redirectUri", URLEncoder.encode(weiXinProperties.getRedirecturi()));
        map.put("state",System.currentTimeMillis()+"");
        return R.ok().data(map);
    }

    @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {
        Map<String,String> resultMap = new HashMap<>();
        //请求https://api.weixin.qq.com/sns/oauth2/access_token, 并传递参数appid,secret,code,grant_type
        StringBuilder tokenBuilder = new StringBuilder();
        StringBuilder tokenAppend = tokenBuilder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String tokenFormat = String.format(tokenAppend.toString(), weiXinProperties.getAppid(), weiXinProperties.getAppsecret(), code);
        String token = HttpClientUtils.get(tokenFormat);

        //获取openid和access_token, 请求https://api.weixin.qq.com/sns/userinfo, 得到微信的信息
        Map<String,String> map = JSONObject.parseObject(token, Map.class);
        String openid = map.get("openid");
        String access_token = map.get("access_token");

        StringBuilder infoBuilder = new StringBuilder();
        StringBuilder infoAppend = infoBuilder.append("https://api.weixin.qq.com/sns/userinfo")
                .append("?access_token=%s")
                .append("&openid=%s");
        String infoFormat = String.format(infoAppend.toString(), access_token,openid);
        String info = HttpClientUtils.get(infoFormat,"UTF-8");

        JSONObject jsonObject = JSONObject.parseObject(info);


        //设置用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setOpenid(openid);
        userInfo.setNickName(jsonObject.getString("nickname"));
        userInfo.setStatus(1);
        userInfoService.save(userInfo);

        //校验手机号是否为空
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        userInfo = userInfoService.getOne(queryWrapper);
        if (StringUtils.isEmpty(userInfo.getPhone())){
            resultMap.put("openid",openid);
        }else {
            resultMap.put("openid","");
        }

        //校验用户状态
        if (userInfo.getStatus() == 0){
            throw new YYGHException(20001,"该用户已被禁用!");
        }

        //显示返回页面信息
        String name = userInfo.getName();
        if (StringUtils.isEmpty(userInfo.getName())){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(userInfo.getName())){
            name = userInfo.getPhone();
        }

        resultMap.put("name",name);
        resultMap.put("token", JwtHelper.createToken(userInfo.getId(),name));

        //跳转到前端页面
        return "redirect:http://localhost:3000/weixin/callback?token="+resultMap.get("token")+ "&openid="+resultMap.get("openid")+"&name="+URLEncoder.encode(resultMap.get("name"),"utf-8");
    }
}
